package com.telecom.oil.smart.controller.mini;

import cn.hutool.core.util.StrUtil;
import com.telecom.oil.common.core.exception.BusinessException;
import com.telecom.oil.common.core.util.R;
import com.telecom.oil.common.security.service.OilUser;
import com.telecom.oil.common.security.util.SecurityUtils;
import com.telecom.oil.common.security.wechat.WechatAuthenticationToken;
import com.telecom.oil.smart.api.enums.RecognizeStatusEnum;
import com.telecom.oil.smart.api.exception.MiniBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.core.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Objects;

public abstract class MiniBaseController {

	@Autowired
	private OAuth2AuthorizationService authorizationService;

	/**
	 * 获取用户信息
	 */
	protected OilUser checkUserWithFullRight(HttpServletRequest request) {
		String token = SecurityUtils.getUserForWechat(request);
		if (StrUtil.isBlank(token)) {
			throw new BusinessException("请先登录");
		}
		OAuth2Authorization oldAuthorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
		if (Objects.isNull(oldAuthorization)) {
			throw new BusinessException("请先登录");
		}
		WechatAuthenticationToken userToken = (WechatAuthenticationToken) Objects.requireNonNull(oldAuthorization)
				.getAttributes().get(Principal.class.getName());
		Object principal = userToken.getPrincipal();
		OilUser user = (OilUser) principal;

		if (user == null) {
			throw new BusinessException("请先登录");
		}
		if (!user.getRecognizeStatus().equals(RecognizeStatusEnum.RECOGNIZED.getCode())) {
			throw new BusinessException("请先认证");
		}
		return user;
	}

	protected OilUser checkUserWithLoginRight(HttpServletRequest request) {
		String token = SecurityUtils.getUserForWechat(request);
		if (StrUtil.isBlank(token)) {
			throw new BusinessException("请先登录");
		}
		OAuth2Authorization oldAuthorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
		if (Objects.isNull(oldAuthorization)) {
			throw new BusinessException("请先登录");
		}
		WechatAuthenticationToken userToken = (WechatAuthenticationToken) Objects.requireNonNull(oldAuthorization)
				.getAttributes().get(Principal.class.getName());
		Object principal = userToken.getPrincipal();
		OilUser user = (OilUser) principal;

		if (user == null) {
			throw new BusinessException("请先登录");
		}
		return user;
	}

}
